package com.share.config.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 通过泛型动态转换用户对象信息
 */
@Component
public class RedisTokenManager {
    //过期时间 /毫秒
    private final static int TOKEN_EXPIRES_SECONDS = 60 * 1000 * 60 * 24 * 365;
    private final static String REDIS_TOKEN_PRE = "token:";
    private final static String HTTP_TOKEN_KEY = "token";

    @Autowired
    private RedisClient redisClient;

    public void fresh(String token) {
        String str = getJsonStr(token);
        if (str != null) {
            setJsonStr(token, str);
        }
    }

    public <T> T getUserInfoAndFresh(HttpServletRequest req, Class<T> cls) {
        String token = getToken(req);
        return getUserInfoAndFresh(token, cls);
    }

    public <T> T getUserInfoAndFresh(String token, Class<T> cls) {
        String str = getJsonStr(token);
        if (str != null) {
            setJsonStr(token, str);
            return JSON.parseObject(str, cls);
        } else {
            return null;
        }
    }


    public <T> T getUserInfo(String token, Class<T> cls) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }

        String jsonStr = getJsonStr(token);
        if (StringUtils.isEmpty(jsonStr)) {
            return null;
        }

        return JSON.parseObject(jsonStr, cls);
    }

    public <T> T getUserInfo(HttpServletRequest req, Class<T> cls) {
        String token = getToken(req);
        return getUserInfo(token, cls);
    }


    public boolean setUserInfo(String token, String jsonStr) {
        return setJsonStr(token, jsonStr);
    }

    public boolean setJsonStr(String token, String jsonStr) {
        redisClient.setex(REDIS_TOKEN_PRE + token, jsonStr, TOKEN_EXPIRES_SECONDS);
        return true;
    }

    public String getJsonStr(String token) {
        String userInfoStr = redisClient.get(REDIS_TOKEN_PRE + token);
        return userInfoStr;
    }

    public boolean delUserInfo(String token) {
        return redisClient.del(REDIS_TOKEN_PRE + token);
    }

    public boolean delUserInfo(HttpServletRequest req) {
        String token = getToken(req);
        return delUserInfo(token);
    }

    private String getToken(HttpServletRequest req) {
        String token = req.getHeader(HTTP_TOKEN_KEY);
        return token;
    }
}
